package com.lxw.multidb.controller;

import cn.tannn.jdevelops.exception.built.BusinessException;
import cn.tannn.jdevelops.result.response.ResultVO;
import com.lxw.multidb.controller.dto.DbConnectionAdd;
import com.lxw.multidb.modules.sql.entity.DbConnection;
import com.lxw.multidb.modules.sql.service.DbConnectionService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/dbConnect")
@RequiredArgsConstructor
@Tag(name = "数据库链接管理")
public class DdConnectionController {

    private final DbConnectionService dbConnectionService;


    @Operation(summary = "新增数据库链接")
    @PostMapping("/add")
    public ResultVO<String> add(@RequestBody @Valid DbConnectionAdd dto) {
        dbConnectionService.add(dto);
        return ResultVO.success();
    }

    @Operation(summary = "获取数据链接列表")
    @GetMapping("/dbUrl")
    public ResultVO<List<DbConnection>> getDbUrl() {
        List<DbConnection> list = dbConnectionService.list();
        return ResultVO.success(list);
    }

    @Operation(summary = "获取数据链接列表")
    @GetMapping("/delete/{id}")
    public ResultVO<String> deleteDb(@PathVariable Integer id) {
        DbConnection dbConnection = dbConnectionService.getById(id).orElseThrow(() -> new BusinessException("为查询到正确数据！"));
        // todo关闭相关数据源
//        databaseMetaService.closeDataSources(dbConnection.to(DbConnectionRequest.class));
        dbConnectionService.deleteById(id);
        return ResultVO.success();
    }

}
